package cn.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 用户登录拦截器
 * Created by WSL on 2016/10/20.
 */
public class Interceptor implements HandlerInterceptor {

    private List<String> beforelogin;
    private List<String> afterlogin;

    /**
     * 在请求方法之前执行，如果返回true，继续执行下一个拦截器，否则不执行下一个拦截器
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println(httpServletRequest.getRequestURI() + "==>" + httpServletRequest.getRequestURL());
        String requri = httpServletRequest.getRequestURI().toString();
        String uemail = (String) httpServletRequest.getSession().getAttribute("uemail");
        if(null != uemail){
            for(String temp:afterlogin){
                if(requri.endsWith(temp)){
                    httpServletResponse.sendRedirect("/");
                    return false;
                }
            }
        }else{
            for(String temp:beforelogin){
                if(requri.endsWith(temp)){
                    httpServletResponse.sendRedirect("/");
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 在请求处理的方法执行之后执行
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在dispatcherservlet之后执行进行清理工作
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    public void setBeforelogin(List<String> beforelogin) {
        this.beforelogin = beforelogin;
    }

    public void setAfterlogin(List<String> afterlogin) {
        this.afterlogin = afterlogin;
    }

}